package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.UserCacheDao;
import com.qdlc.p2p.dal.dao.UserIdentifyDao;
import com.qdlc.p2p.dal.dao.UserVipApplyDao;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.dto.UserVipApply;
import com.qdlc.p2p.dal.model.UserIdentifyModel;
import com.qdlc.p2p.dal.model.UserModel;
import com.qdlc.p2p.dal.model.UserVipApplyModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 认证信息
 *
 * @author sj
 * @version 2.0
 * @since 2014年2月17日17:27:02
 */
@Repository("userIdentifyDao")
public class UserIdentifyDaoImpl extends BaseDaoImpl<UserIdentify> implements UserIdentifyDao {

    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(UserCreditDaoImpl.class);

    @Resource
    private UserCacheDao userCacheDao;
    @Resource
    private UserVipApplyDao userVipApplyDao;

    @Override
    @Cacheable(value="userIdentify", key="#userId")
    public UserIdentify findByUserId(long userId) {
        return this.findObjByProperty("userId", userId);
    }

    @Override
    @CachePut(value="userIdentify", key="#userIdentify.userId")
	public UserIdentify update(UserIdentify userIdentify) {
		return super.update(userIdentify);
	}

	@Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyRealnameStatus(long userId, int status, int preStatus) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET real_name_status = :status " + "WHERE user_id = :userId "
                + "AND real_name_status = :preStatus";
        String[] names = new String[]{"status", "userId", "preStatus"};
        Object[] values = new Object[]{status, userId, preStatus};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新用户实名认证状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyRealnameStatus(long userId, int status) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET real_name_status = :status , real_name_verify_time = now() " + "WHERE user_id = :userId ";
        String[] names = new String[]{"status", "userId"};
        Object[] values = new Object[]{status, userId};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新用户实名认证状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyEmailStatus(long userId, int status, int preStatus) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET email_status = :status " + "WHERE user_id = :userId "
                + "AND email_status = :preStatus";
        String[] names = new String[]{"status", "userId", "preStatus"};
        Object[] values = new Object[]{status, userId, preStatus};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新用户邮箱激活状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyMobilePhoneStatus(long userId, int status, int preStatus) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET mobile_phone_status = :status "
                + "WHERE user_id = :userId " + "AND mobile_phone_status = :preStatus";
        String[] names = new String[]{"status", "userId", "preStatus"};
        Object[] values = new Object[]{status, userId, preStatus};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新用户手机绑定状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }
    
    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyTppMobilePhoneStatus(long userId, int status, int preStatus) {
    	String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET tpp_mobile_phone_status = :status "
    			+ "WHERE user_id = :userId " ;
    	String[] names = new String[]{"status", "userId"};
    	Object[] values = new Object[]{status, userId};
    	int count = updateBySql(nativeSql, names, values);
    	if (count != 1) {
    		throw new UserException("更新用户绑定认证信息状态失败！", 1);
    	}
    	this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyVipStatus(long userId, int status, int preStatus) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify SET vip_status = :status "
                + " WHERE user_id = :userId and vip_status = :preStatus";
        String[] names = new String[]{"status", "userId", "preStatus"};
        Object[] values = new Object[]{status, userId, preStatus};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新vip状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void modifyMobilePhoneStatus(long userId, int status) {
        String nativeSql = "UPDATE " + Global.DB_PREFIX + "user_identify " + "SET mobile_phone_status = :status , mobile_phone_verify_time =now() "
                + "WHERE user_id = :userId ";
        String[] names = new String[]{"status", "userId"};
        Object[] values = new Object[]{status, userId};
        int count = updateBySql(nativeSql, names, values);
        if (count != 1) {
            throw new UserException("更新用户手机绑定状态失败！", 1);
        }
        this.refresh(this.findByUserId(userId));
    }

    @Override
    @CacheEvict(value="userIdentify", key="#userId")
    public void userAttestationEdit(long id, long userId, String realNameVerifyRemark, int realNameStatus, Operator operator) {
        String jpql = "UPDATE UserIdentify SET realNameStatus = :realNameStatus, "
                + "realNameVerifyTime= :realNameVerifyTime,realNameVerifyRemark= :realNameVerifyRemark WHERE id = :id";
        Query query = em.createQuery(jpql);
        query.setParameter("realNameStatus", realNameStatus);
        query.setParameter("realNameVerifyTime", DateUtil.getNow());
        query.setParameter("realNameVerifyRemark", realNameVerifyRemark);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        if (result != 1) {
            throw new UserException("实名认证审核失败！");
        }
    }

    @Override
    public int countByRealName(int status) {
        QueryParam param = QueryParam.getInstance().addParam("realNameStatus", status);
        return countByCriteria(param);
    }

    @Override
    public int countByMobilePhone(String mobilePhone) {
        QueryParam param = QueryParam.getInstance().addParam("user.mobilePhone", mobilePhone)
                .addParam("mobilePhoneStatus", 1);
        return countByCriteria(param);
    }

    @Override
    public int countByEmail(String email) {
        QueryParam param = QueryParam.getInstance().addParam("user.email", email).addParam("emailStatus", 1);
        return countByCriteria(param);
    }

    @Override
    public PageDataList<UserIdentifyModel> findUserIdentifylist(UserIdentifyModel model) {
        QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
        String searchName = model.getSearchName();
        if (!StringUtil.isBlank(searchName)) {// 模糊查询条件
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, searchName.trim());
            SearchFilter orFilter2 = new SearchFilter("user.realName", Operators.LIKE, searchName.trim());
            param.addOrFilter(orFilter1, orFilter2);
        } else {// 精确查询条件
            if (model.getEmailStatus() != -3) {
                if (model.getVipStatus() != -2) {
                    param.addParam("vipStatus", model.getVipStatus());
                }
                if (model.getEmailStatus() != -2) {
                    param.addParam("emailStatus", model.getEmailStatus());
                }
                if (model.getRealNameStatus() != -2) {
                    param.addParam("realNameStatus", model.getRealNameStatus());
                }
                if (model.getMobilePhoneStatus() != -2) {
                    param.addParam("mobilePhoneStatus", model.getMobilePhoneStatus());
                }
                if (model.getUser() != null && !StringUtil.isBlank(model.getUser().getUserName())) {
                    param.addParam("user.userName", model.getUser().getUserName().trim());
                }
            }
        }
        param.addOrder(OrderType.DESC, "id");
        PageDataList<UserIdentify> pageDataList = this.findPageList(param);
        PageDataList<UserIdentifyModel> pageDateList_ = new PageDataList<UserIdentifyModel>();
        List<UserIdentifyModel> list = new ArrayList<UserIdentifyModel>();
        pageDateList_.setPage(pageDataList.getPage());
        for (int i = 0; i < pageDataList.getList().size(); i++) {
            UserIdentify userIdentify = (UserIdentify) pageDataList.getList().get(i);
            UserIdentifyModel um = UserIdentifyModel.instance(userIdentify);
            User user = UserUtils.getUserById(userIdentify.getUserId());
            if (user != null) {
                um.setUserName(user.getUserName());
                um.setRealName(user.getRealName());
                um.setEmail(user.getEmail());
                um.setMobilePhone(user.getMobilePhone());
            }
            list.add(um);
        }
        pageDateList_.setList(list);
        return pageDateList_;
    }

    @Override
    public PageDataList<UserIdentifyModel> findUserIdentifylist(int pageNumber, int pageSize, UserIdentify model, String searchName) {
        QueryParam param = QueryParam.getInstance().addPage(pageNumber, pageSize);
        if (!StringUtil.isBlank(searchName)) {// 模糊查询条件
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, searchName);
            SearchFilter orFilter2 = new SearchFilter("user.realName", Operators.LIKE, searchName);
            param.addOrFilter(orFilter1, orFilter2);
        } else {// 精确查询条件
            if (model != null) {
                if (model.getEmailStatus() != -2) {
                    param.addParam("emailStatus", model.getEmailStatus());
                }
                if (model.getRealNameStatus() != -2) {
                    param.addParam("realNameStatus", model.getRealNameStatus());
                }
                if (model.getMobilePhoneStatus() != -2) {
                    param.addParam("mobilePhoneStatus", model.getMobilePhoneStatus());
                }
                User user = UserUtils.getUserById(model.getUserId());
                if (user != null && !StringUtil.isBlank(user.getUserName())) {
                    param.addParam("user.userName", Operators.LIKE, user.getUserName());
                }
            }
        }
        param.addOrder(OrderType.DESC, "id");
        PageDataList<UserIdentify> pageDataList = this.findPageList(param);
        PageDataList<UserIdentifyModel> pageDateList_ = new PageDataList<UserIdentifyModel>();
        List<UserIdentifyModel> list = new ArrayList<UserIdentifyModel>();
        pageDateList_.setPage(pageDataList.getPage());
        for (int i = 0; i < pageDataList.getList().size(); i++) {
            UserIdentify userIdentify = (UserIdentify) pageDataList.getList().get(i);
            UserIdentifyModel um = UserIdentifyModel.instance(userIdentify);
            User user = UserUtils.getUserById(userIdentify.getUserId());
            if (user != null) {
                String userName = user.getUserName();
                um.setUserName(userName);
                um.setRealName(user.getRealName());
                um.setEmail(user.getEmail());
                um.setMobilePhone(user.getMobilePhone());
            }
            list.add(um);
        }
        pageDateList_.setList(list);
        return pageDateList_;
    }

    @Override
    public PageDataList<UserModel> userModelList(int pageNumber, int pageSize, UserIdentify model, String searchName) {
        QueryParam param = QueryParam.getInstance().addPage(pageNumber, pageSize);
        if (StringUtil.isNotBlank(searchName)) {// 模糊查询条件
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, searchName);
            SearchFilter orFilter2 = new SearchFilter("user.realName", Operators.LIKE, searchName);
            param.addOrFilter(orFilter1, orFilter2);
        } else {// 精确查询条件
            if (model != null) {
                if (model.getRealNameStatus() != 99) {
                    param.addParam("realNameStatus", model.getRealNameStatus());
                }
                User user = UserUtils.getUserById(model.getUserId());
                if (user != null) {
                    if (StringUtil.isNotBlank(user.getUserName())) {
                        param.addParam("user.userName", Operators.LIKE, user.getUserName());
                    }
                    if (StringUtil.isNotBlank(user.getRealName())) {
                        param.addParam("user.realName", Operators.LIKE, user.getRealName());
                    }
                    if (StringUtil.isNotBlank(user.getCardId())) {
                        param.addParam("user.cardId", Operators.LIKE, user.getCardId());
                    }
                }
            }
        }
        param.addOrder(OrderType.DESC, "realNameVerifyTime");
        PageDataList<UserIdentify> pageDataList = this.findPageList(param);
        PageDataList<UserModel> pageDataList_ = new PageDataList<UserModel>();
        List<UserModel> list = new ArrayList<UserModel>();
        pageDataList_.setPage(pageDataList.getPage());
        if (pageDataList.getList().size() > 0) {
            for (int i = 0; i < pageDataList.getList().size(); i++) {
                UserIdentify userIdentify = (UserIdentify) pageDataList.getList().get(i);
                UserModel userModel = null;
                User user = UserUtils.getUserById(userIdentify.getUserId());
                if (user == null) {
                    userModel = new UserModel();
                    userModel.setUserCache(null);
                    userModel.setUserIdentify(userIdentify);
                    userModel.setUserName("<font color='red'>该用户已被删除</font>");
                } else {
                    userModel = UserModel.instance(user);
                    userModel.setUserCache(userCacheDao.findByUserId(user.getUserId()));
                    userModel.setUserIdentify(userIdentify);
                }
                list.add(userModel);
            }
        }
        pageDataList_.setList(list);
        return pageDataList_;
    }

    @Override
    public PageDataList<UserModel> userModelList(UserIdentifyModel model) {
        QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
        String searchName = model.getSearchName();
        if (!StringUtil.isBlank(searchName)) {// 模糊查询条件
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, searchName.trim());
            SearchFilter orFilter2 = new SearchFilter("user.realName", Operators.LIKE, searchName.trim());
            SearchFilter orFilter3 = new SearchFilter("user.cardId", Operators.LIKE, searchName.trim());
            param.addOrFilter(orFilter1, orFilter2, orFilter3);
        } else {// 精确查询条件
            if (model.getRealNameStatus() != -2) {
                param.addParam("realNameStatus", model.getRealNameStatus());
            }
            if (model.getUser() != null && !StringUtil.isBlank(model.getUser().getUserName())) {
                param.addParam("user.userName", Operators.LIKE, model.getUser().getUserName().trim());
            }
            if (model.getUser() != null && !StringUtil.isBlank(model.getUser().getRealName())) {
                param.addParam("user.realName", Operators.LIKE, model.getUser().getRealName().trim());
            }
            if (model.getUser() != null && !StringUtil.isBlank(model.getUser().getCardId())) {
                param.addParam("user.cardId", Operators.EQ, model.getUser().getCardId());
            }
        }
        param.addOrder(OrderType.DESC, "realNameVerifyTime");
        PageDataList<UserIdentify> pageDataList = this.findPageList(param);
        PageDataList<UserModel> pageDataList_ = new PageDataList<UserModel>();
        List<UserModel> list = new ArrayList<UserModel>();
        pageDataList_.setPage(pageDataList.getPage());
        if (pageDataList.getList().size() > 0) {
            for (int i = 0; i < pageDataList.getList().size(); i++) {
                UserIdentify userIdentify = (UserIdentify) pageDataList.getList().get(i);
                UserModel userModel = null;
                User user = UserUtils.getUserById(userIdentify.getUserId());
                if (user == null) {
                    userModel = new UserModel();
                    userModel.setUserCache(null);
                    userModel.setUserIdentify(userIdentify);
                    userModel.setUserName("<font color='red'>该用户已被删除</font>");
                } else {
                    userModel = UserModel.instance(user);
                    userModel.setUserCache(userCacheDao.findByUserId(user.getUserId()));
                    userModel.setUserIdentify(userIdentify);
                }
                list.add(userModel);
            }
        }
        pageDataList_.setList(list);
        return pageDataList_;
    }

    @Override
    public PageDataList<UserVipApplyModel> vipApplyList(int pageNumber, int pageSize, UserVipApplyModel model) {
        QueryParam param = QueryParam.getInstance().addPage(pageNumber, pageSize);
        if (!StringUtil.isBlank(model.getSearchName())) {
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, model.getSearchName().trim());
            SearchFilter orFilter2 = new SearchFilter("user.realName", Operators.LIKE, model.getSearchName().trim());
            param.addOrFilter(orFilter1, orFilter2);
        }
        if (!StringUtil.isBlank(model.getUserName())) {
            param.addParam("user.userName", Operators.LIKE, model.getUserName().trim());
        }
        if (StringUtil.isNotBlank(model.getStartTime())) {
            Date start = DateUtil.valueOf(model.getStartTime() + " 00:00:00");
            param.addParam("addTime", Operators.GTE, start);
        }
        if (StringUtil.isNotBlank(model.getEndTime())) {
            Date end = DateUtil.valueOf(model.getEndTime() + " 23:59:59");
            param.addParam("addTime", Operators.LTE, end);
        }
        if (model.getStatus() < 3) {
            param.addParam("status", model.getStatus());
        }
        param.addOrder(OrderType.DESC, "addTime");
        PageDataList<UserVipApply> pageDataList = userVipApplyDao.findPageList(param);
        PageDataList<UserVipApplyModel> pageDataList_ = new PageDataList<UserVipApplyModel>();
        List<UserVipApplyModel> list = new ArrayList<UserVipApplyModel>();
        pageDataList_.setPage(pageDataList.getPage());
        if (pageDataList.getList().size() > 0) {
            for (int i = 0; i < pageDataList.getList().size(); i++) {
                UserVipApply user = (UserVipApply) pageDataList.getList().get(i);
                user.getUser().getUserId();
                UserVipApplyModel userModel = UserVipApplyModel.instance(user);
                list.add(userModel);
            }
        }
        pageDataList_.setList(list);
        return pageDataList_;
    }

}
